#coding: utf-8

import re

def format_element(bfo):
	authors = []
	for a in bfo.fields("720__a"):
		author = ""
		if "," in a:
			s = re.split("\s*,\s+", a)
			author = s[0] + ","
			for n in re.split("\s+", s[1].strip()):
				n = n.capitalize()
				if re.match("^Ch.*", n):
					author += " Ch."
				else:
					author += " %s." % n.decode("utf-8")[0].encode("utf-8")
					
		else:
			author = a
		authors.append(author)
	date = bfo.field("046__k")
	if date:
		date = " (%s)." % date[:4]
	name = bfo.field("24500a")
	if name:
		name = " %s." % name
	journalName = bfo.field("7731_t")
	if journalName:
		journalName = " <em>%s</em>," % journalName
	details = bfo.field("7731_g")
	if details:
		details = re.sub(",?\s*\(\d+\)\s*$", "", details)
		details = " %s." % details
	
	idrec = bfo.control_field("001")
	
	return "%s%s%s%s%s Dostupný z: http://www.nusl.cz/ntk/nusl-%s" %  (", ".join(authors), date, name, journalName, details, idrec)
	
def escape_values(bfo):
    """
    Called by BibFormat in order to check if output of this element
    should be escaped.
    """
    return 0
			
		
if __name__ == "__main__":
	from invenio.bibformat_engine import BibFormatObject
	print format(BibFormatObject(68))

